
import { IncomingMessage, ServerResponse } from "http";
import { v4 as uuid } from "uuid";
import fs from 'fs';
import path from 'path';

const __path = path.join(__dirname, '../../../../src');

/** 创建模块 */
export const add = async (req: IncomingMessage, res: ServerResponse) => {
    let body = '';
    req.on('data', chunk => { body += chunk.toString() });
    req.on('end', () => {
        try {
            const { id, templateId, name, icon='', tag='default', description='一个模块' } = JSON.parse(body);
            const { files }: { files: string[] } = JSON.parse(fs.readFileSync(path.join(__dirname, '../../module.template', templateId, 'index.json'), 'utf-8'));
            const modulePath = path.join(__path, 'modules', id);

            // 创建模块目录
            mkdir(modulePath);
            files.forEach(filePath => { mkdir(path.dirname(path.join(modulePath, filePath))) });

            // 复制文件
            files.forEach(filePath => {
                // 读取文件内容
                let content = fs.readFileSync(path.join(__dirname, '../../module.template', templateId, filePath), 'utf-8');
                
                // 替换内容
                content = content.replace(/\{\{key\}\}/g, uuid());
                content = content.replace(/\{\{name\}\}/g, name);
                content = content.replace(/\{\{id\}\}/g, id);
                content = content.replace(/\{\{icon\}\}/g, icon);
                content = content.replace(/\{\{tag\}\}/g, tag);
                content = content.replace(/\{\{description\}\}/g, description);

                // 写入文件
                fs.writeFileSync(path.join(modulePath, filePath), content);
            });

            res.statusCode = 200;
            res.end();
        } catch (error) {
            console.log(body);
            res.statusCode = 500;
            res.statusMessage = error instanceof Error ? error.message : '未知错误';
            res.end();
        }
    });
}

/** 创建目录 */
export const mkdir = (source: string) => {
    // 路径数组
    const pathArr = source.split(path.sep);
    pathArr.forEach((_, i) => {
        const dir = pathArr.slice(0, i + 1).join(path.sep);
        if (!fs.existsSync(dir) && dir !== '') {
            fs.mkdirSync(dir);
        }
    });
}